package Terminal;

import Commands.Command;
import Commands.TerminalCommand;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Authors: Henrique Alberto Rusa and Danilo Barbosa Porto
 * Date: 05/12/13
 *
 *  Terminal class implements the interface of application and user considering the input of the user when he/she
 *  types an argument on the created terminal.
 */
public class Terminal {

    /*
     *  List of all the Terminal listeners added by the method addListener()
     */
    private List<TerminalListener> listeners;

    /*
     *  Buffered reader to read the user input
     */
    private Scanner reader;

    /*
     *  Constructor of the class, where it is allocated memory to the list, buffered reader and get the
     *  terminal running.
     */
    public Terminal(){
        listeners = new ArrayList<TerminalListener>();
        reader = new Scanner(System.in);
    }

    /*
     *  Method start that initiates the execution of the terminal itself.
     *  Thus it will keep reading input from the user and process it as a command to the listeners of the terminal.
     */
    public void start(){

        // Strings of control, the split one and the command itself
        String read;

        // keep always reading from input
        while(true){
            // read input from user
            read = reader.nextLine();

            // trim blank spaces to split after
            read = read.trim();
            // creates a command and warn all the listeners of the event
            this.newArgument(new TerminalCommand(read));
        }
    }

    /*
     *  Method that adds listeners to the terminal, where the list will be used to warn all the listening classes
     *  when an event occurs.
     */
    public void addListener(TerminalListener onAdd){
        this.listeners.add(onAdd);
    }

    /*
     *  Method that will get all the listeners of the class and warn them of a event.
     *  The command will be created when the call is done to the method.
     */
    public void newArgument(Command evt){
        for(TerminalListener element : listeners){
            element.onCommandType(evt);
        }
    }

}
